package com.hunau.iot.server.nettyserver;

import com.hunau.iot.server.utils.SpringContextUtils;
import com.hunau.system.domain.TbIoterminal;
import com.hunau.system.service.impl.TbIoterminalServiceImpl;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 存储整个工程的全局配置
 * @author liuyazhuang
 *
 */
public class ChannelManage {
	private static TbIoterminalServiceImpl tbIoterminalService = (TbIoterminalServiceImpl) SpringContextUtils.getBeanByClass(TbIoterminalServiceImpl.class);
	/**
	 *  不需要接收数据的集合, MIME-1
	 */
	public static ConcurrentHashMap<String , Integer> dontIn = new ConcurrentHashMap<>();
	//初始化不需要接收数据的集合
	static {
		List<TbIoterminal> tbIoterminals = tbIoterminalService.selectTbIoterminalList(new TbIoterminal());
		for (TbIoterminal tb : tbIoterminals){
			if(tb.getStatus()==0){
				dontIn.put(tb.getImei(),1);
			}
		}
	}
	/**
	 * 存储每一个客户端接入进来时的channel对象
	 */
	public static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	/**保存终端连接信息  MIME：channel**/
	public static ConcurrentHashMap<String,Channel> dev1Mime = new ConcurrentHashMap<>();
	/**保存终端连接信息  channelId：MIME**/
	public static ConcurrentHashMap<String,String> dev2id = new ConcurrentHashMap<>();
	/**读锁**/
    private static ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(true);


	/**
	 * 根据终端MIME开始接收数据
	 * @param MIME
	 * @return
	 */
	public static boolean startInDataChannelByMIME(String MIME){
		Channel channel = dev1Mime.get(MIME);
		if(channel == null){
			return false;
		}else {
			dontIn.remove(MIME);
			return true;
		}
	}
	/**
	 * 根据终端MIME停止接收数据
	 * @param MIME
	 * @return
	 */
    public static boolean stopInDataChannelByMIME(String MIME){
		Channel channel = dev1Mime.get(MIME);
		if(channel == null){
			return false;
		}else {
			dontIn.put(MIME,1);
			return true;
		}
	}

}
